<template>
    <div class="MFormTitle" :style="titleStyle">
        <span :style="getStyle()">{{ controlName(metadata) }}</span>
        <span v-if="localRequired" class="require-symbol">*</span>
        <span v-if="ruleState.state" class="m-prompt">{{ ruleState.msg }}</span>
    </div>
</template>

<script>
import checkRule from '@/views/modules/form/customForm/js/checkRule'
export default {
    name: "MFormTitle",
    mixins:[checkRule],
    inject:{
        formVm:{}
    },
    props: {
        //标题名
        name: {
            type: Object
        },
        //规则必填，字段长度
        rules: {
            type: Array
        },
        value: "",
        //必填
        required: {
            default: () => {
                return false
            },
        },
        //只读
        readOnly: {
            default: () => {
                return false
            },
        },
        metadata: {
            type: Object
        },
        isDialog:{},
        data:{}
    },
    data() {
        return {
            ruleState: {
                state: false,
                msg: ''
            },
            globalConfig:{}
        }
    },
    created() {
        this.rule();
        this.globalConfig =  uni.getStorageSync('globalConfig')  ;
    },
    computed: {
        titleStyle(){
            let style = this.metadata.style ;
            let styles = {}
            for (let key in style){
                let k = key ;
                if(key && key.includes('-')){
                    k = key.split('-');
                    k = k.map((val,idx)=>idx === 0? val : val.charAt(0).toLocaleUpperCase()+val.substring(1)).join('')
                }
                if(['textAlign','fontSize','lineHeight','fontWeight','color'].includes(k)){
                    styles[key] = style[key];
                }
            }
            return styles
        },
        /**
         * 判断是否必填.
         */
        localRequired() {
            if (this.readOnly) {
                return false
            } else {
                return this.required
            }
        },
        controlName(){
            let self = this;
            let { formVm ,isDialog} = this;
            return (item)=>{
                let {nameCondition} = item.control;
                if(nameCondition && !isDialog){
                    try {
                        if(nameCondition.indexOf('return ') === -1){
                            nameCondition = `return ${nameCondition}`;
                        }
                        let fn = new Function('data','self','row',nameCondition).call(formVm,formVm.data,formVm,self.data);
                        return fn
                    }catch (e) { }
                }
                return self.$i18(item.name) ;
            }
        }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        //校验规则和表达式
        rule() {
            this.ruleState = {state: false, msg: ''};
            //如果没有规则则直接返回.
            if(!this.rules){
                return;
            }

            for (let res of this.rules){
                //校验长度
                if(res.max != undefined && res.max != 0){
                    let _max = res.max + '';
                    if((['upload','image','textarea'].includes(this.metadata.type)) && this.metadata.type === 'clob'){
                        //上传附件或图片大文本 不验证字段长度；
                        continue ;
                    }
                    if(_max.includes('.') && typeof this.value === 'number'){
                        let value = this.value + '';
                        //如果长度有小数点
                        let maxAr = _max.split('.');
                        let rule1 = maxAr[0],rule2 = maxAr[1];
                        let _valueArr = value.split('.');
                        if(!this.isValNull(value,this.metadata) && _valueArr[1] && _valueArr[1].length > rule2){
                            return {state:true, msg:this.i18n('exceeded','数字小数位超出！')}
                        }else if (!this.isValNull(value) && _valueArr[0].length > (Number(rule1) - Number(rule2))) {
                            //如果长度设置为零 则没有长度限制
                            this.ruleState = {
                                state: true,
                                msg: res.message + parseInt(res.max)
                            }
                            return
                        }
                    }else if (!this.isValNull(this.value) && this.changeStrLength(this.value,this.metadata) > res.max) {
                        //如果长度设置为零 则没有长度限制
                        this.ruleState = {
                            state: true,
                            msg: res.message + parseInt(res.max)
                        }
                        return
                    }
                }
                //检验规则表达式
                if (res.pattern) {
                    let regular = new RegExp(res.pattern, 'g');
                    //正则表达式数据不为空的时候才校验 ;
                    if (!this.isValNull(this.value) && !regular.test(this.value)) {
                        this.ruleState = {
                            state: true,
                            msg: res.message
                        }
                    }
                }
            }
        },
        /**
         * 判断值是否为空
         * @param val 当前控件的值
         * @param type 当前控件的类型
         * @returns {boolean} 如果值为空则返回true
         */
        isValNull(val, type) {
            //判断值是否为空,为空返回true
            let value = typeof val === 'string' ? val.trim() : val;
            if (value || (value === 0 && type !== 'score')) {
                //控件为0也算有值，但是评分控件除外
                if (Array.isArray(value) && value.length === 0) {
                    return true;
                }
                return false;
            }
            return true;
        },
        getStyle(){
            let style = {};
            if(this.globalConfig){
                style = {
                    color:this.globalConfig.color,
                    fontSize:this.globalConfig.fontSize=='14px'?'0.9rem':this.globalConfig.fontSize,
                    fontWeight:this.globalConfig.fontWeight
                }
            }
            return style
        }
    },
    watch: {
        value: {
            handler() {
                this.rule()
            },
            deep: true
        }
    }
}
</script>

<style scoped>
.MFormTitle{
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.require-symbol {
    display: inline-block;
    margin-left: 4px;
    width: auto;
    color: red;
    margin-right: 2px;
}

.m-prompt {
    color: red;
    font-size: 12px;
    margin-left: 5px;
}
</style>
